package bll

import (
	"auth/collector/logger"
	"auth/store/postgres"
	"context"
	"github.com/pkg/errors"
	"time"

	"auth/event"
	"auth/model"
	"auth/model/entity"
	"auth/store"
)

type resource struct {
	iResource store.IResource
}

var Resource = &resource{}

func (a *resource) init() func() {
	a.iResource = postgres.Resource
	return func() {}
}

func (a *resource) onEvent(*event.Data) {}

func (a *resource) Create(ctx context.Context, in *model.ResourceCreateRequest) error {
	var (
		err         error
		byParameter *model.ResourceByParameterRequest
		count       int64
	)
	byParameter = &model.ResourceByParameterRequest{
		Name:     in.Name,
		Resource: in.Resource,
	}
	if count, err = a.iResource.FindByParameterCount(byParameter); err != nil {
		// todo 处理
		logger.Errorf("", in.Name)
		return err
	}
	if count != 0 {
		// todo 处理
		logger.Errorf("", in.Name)
		return errors.New("已存在数据，请修改")
	}

	c := buildResource(in)
	if _, err = a.iResource.Create(c); err != nil {
		// todo 处理
		logger.Errorf("", in.Name)
		return err
	}
	return err
}

func (a *resource) Update(ctx context.Context, in *model.ResourceUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)
	dict["name"] = in.Name
	dict["resource"] = in.Resource

	return a.iResource.Update(in.ID, dict)
}

func (a *resource) Delete(ctx context.Context, in *model.ResourceDeleteRequest) error {
	return a.iResource.Delete(in.ID)
}

func (a *resource) List(ctx context.Context, in *model.ResourceListRequest) (*model.ResourceListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Resource
		out   = &model.ResourceListResponse{}
	)

	if total, list, err = a.iResource.List(in); err != nil {
		return nil, err
	}

	out.Total = total
	out.Data = model.ResourcesEntityToDto(list)

	return out, nil
}

func buildResource(in *model.ResourceCreateRequest) *entity.Resource {
	// todo: check the entity is required
	return &entity.Resource{

		Name: in.Name,

		Resource: in.Resource,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
